const path = require('path');
const fs = require('fs-extra');
const inquirer = require('inquirer');
const chalk = require('chalk');
const { exec } = require('child_process')

async function create(name, options) {
    // 获取当前的目录地址
    const cwd = process.cwd();
    // 创建项目的目录地址
    const projectCwd = path.join(cwd, name);

    // 如果当前目录下存在同名的项目名字文件夹
    if (fs.existsSync(projectCwd)) {
        // 询问用户是否覆盖
        const { action } = await inquirer.prompt([{
            name: 'action',
            type: 'list',
            message: '项目文件夹已经存在:',
            choices: [{
                    name: '覆盖',
                    value: 'overwrite'
                },
                {
                    name: '取消',
                    value: false
                }
            ]
        }])
        if (!action) { // 取消
            return;
        } else if (action === 'overwrite') { // 覆盖
            await fs.remove(projectCwd);
        }
    }

    // 选择模版下载
    const { url } = await inquirer.prompt([{
        name: 'url',
        type: 'list',
        message: '请选择一个模版来创建项目',
        choices: [
            {
                name: 'react-template',
                value: 'https://gitee.com/codingcoder/webpack5-react-template.git'
            },
            {
                name: 'vue-template',
                value: 'https://gitee.com/codingcoder/webpack5-react-template.git'
            },
            {
                name: 'h5-template',
                value: 'https://gitee.com/codingcoder/webpack5-react-h5-template.git'
            }
        ]
    }]);
    pullProject(url, name)
}

// 拉取项目
function pullProject (url, name) {
    exec(`git clone ${url} ${name}`, (error, stdout, stderr) => {
        if (error) {
            console.log(chalk.red(error));
            process.exit();
        }
        console.log(chalk.green('Project Create Success'));
        process.exit();
    })
}




module.exports = create